package com.example.administrator.kotlintabviewpagerfragment.fragment

import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.design.widget.TabLayout.OnTabSelectedListener
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.administrator.kotlintabviewpagerfragment.R
import com.example.administrator.kotlintabviewpagerfragment.adapter.TabPagerAdapter
import kotlinx.android.synthetic.main.tab1_fragment.view.*

/**
 * Created by ZLG on 2017/6/25.
 */
class Tab1Fragment : android.support.v4.app.Fragment(), OnTabSelectedListener {

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {

        val position = tab!!.position
        Log.e(">>>>>>>>>>>","<<<<<<<<<<<${position}<<<<<<<")
        view!!.view_pager.currentItem = tab!!.position
    }
    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }
    val titles= listOf<String>("Java","Android","C#","Kotlin")

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            val view = inflater!!.inflate(R.layout.tab1_fragment, container, false)
            /**
             * 在这里声明下   必须用   view.调用   不然控件会NPE
             * */
            view.tab_layout.tabMode=TabLayout.MODE_FIXED
            setTab(view)
            view.tab_layout.addOnTabSelectedListener(this)
            setItem(view)
            return view
    }

    fun setTab(view : View)  {
        val tab1: TabChildFragment1 = TabChildFragment1()
        val tab2: TabChildFragment1 = TabChildFragment1()
        val tab3: TabChildFragment1 = TabChildFragment1()
        val tab4: TabChildFragment1 = TabChildFragment1()
        var lsit = listOf<Fragment>(tab1, tab2, tab3,tab4)
        view.view_pager.adapter = TabPagerAdapter(lsit, childFragmentManager)
        view.tab_layout.setupWithViewPager(view.view_pager)
    }
    /**
     * 设置tabitem
     * */
    fun setItem(view : View) {
        view.tab_layout.getTabAt(0)?.customView = getTabView(0)
        view.tab_layout.getTabAt(1)?.customView = getTabView(1)
        view.tab_layout.getTabAt(2)?.customView = getTabView(2)
        view.tab_layout.getTabAt(3)?.customView = getTabView(3)
    }

    fun getTabView(position: Int): View {
        val view = LayoutInflater.from(context).inflate(R.layout.child_fragment_title, null)
        val child_title = view.findViewById(R.id.child_title) as TextView
        child_title.text=titles[position]
        return view
    }

}